﻿using System.ServiceModel.Channels;

namespace RockBus.DataContracts
{
    public static class MessageExtensions
    {
        public static void AddRoutingHeader(this Message message, RoutingHeader routingHeader)
        {
            MessageHeader header = MessageHeader.CreateHeader(
                RoutingHeader.HeaderName,
                StringConstants.RockBusNamespace,
                routingHeader);
            message.Headers.Add(header);
        }

        public static RoutingHeader GetRoutingHeader(this Message message, bool remove = false)
        {
            int messageHeaderIndex = message.Headers.FindHeader(
                RoutingHeader.HeaderName,
                StringConstants.RockBusNamespace);

            RoutingHeader routingHeader = null;
            if (messageHeaderIndex >= 0)
            {
                routingHeader = message.Headers.GetHeader<RoutingHeader>(messageHeaderIndex);
                if (remove)
                {
                    message.Headers.RemoveAt(messageHeaderIndex);
                }
            }
            return routingHeader;
        }
    }
}